﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DataModels.Common;
using GenericTools;
using GenericTools.Models;

namespace ReportingManagement.Components.AutoReminder
{
    public partial class SetHolidays : Form
    {
        private const int YEARS_TO_ADD = 3;
        private const int YEARS_TO_SUBTRACT = 2;

        private const int HOLIDAY_DATE_COLUMN_INDEX = 0;
        private const int HOLIDAY_NAME_COLUMN_INDEX = 1;

        private const int GENERAL_MONTH_START = 1;
        private const int GENERAL_MONTH_END = 31;
        private const int MONTH_TEXT_LENGH = 3;

        private List<string> monthText = new List<string>()
        {
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", 
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        };

        public SetHolidays()
        {
            InitializeComponent();
            PopulateCalendarYears();
            cboYear.Text = DateTime.Now.Year.ToString();
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            CheckCalendarYear();
        }

        private void CheckCalendarYear()
        {
            string sCalendarYear = cboYear.Text;
            int currentYear = DateTime.Now.Year;
            int iCalendarYear = currentYear;
            bool converted = int.TryParse(sCalendarYear, out iCalendarYear);
            if (converted)
            {
                int someYearsBack = currentYear - YEARS_TO_SUBTRACT;
                int someYearsAfter = currentYear + YEARS_TO_ADD;
                if (someYearsBack <= iCalendarYear && iCalendarYear <= someYearsAfter)
                {
                    DataTable dataTable = Utilities.GetHolidays(iCalendarYear);
                    dataTable.Columns.Remove("CalendarYear");
                    dgvHolidays.DataSource = dataTable;
                    btnSave.Enabled = true;
                    btnReset.Enabled = true;
                }
                else
                {
                    btnSave.Enabled = false;
                    btnReset.Enabled = false;
                }
            }
            else
            {
                btnSave.Enabled = false;
                btnReset.Enabled = false;
            }
        }

        private void PopulateCalendarYears()
        {
            cboYear.Items.Clear();
            DataTable dataTable = Utilities.GetCalendarYears();
            foreach (DataRow r in dataTable.Rows)
            {
                int calendarYear = int.Parse(r["CalendarYear"].ToString());
                cboYear.Items.Add(calendarYear);
            }
        }

        private void cboYear_TextChanged(object sender, EventArgs e)
        {
            CheckCalendarYear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            List<string> holidayNames = new List<string>();
            List<string> holidayDates = new List<string>(); 
            int calendarYear = int.Parse(cboYear.Text);

            for (int i = 0; i < dgvHolidays.Rows.Count; i++)
            {
                DataGridViewRow r = dgvHolidays.Rows[i];
                if (i == dgvHolidays.Rows.Count - 1) // This is the last row
                {
                    if (r.Cells[HOLIDAY_DATE_COLUMN_INDEX].Value == null && 
                        r.Cells[HOLIDAY_NAME_COLUMN_INDEX].Value == null) continue;
                }

                string holidayDate = r.Cells[HOLIDAY_DATE_COLUMN_INDEX].Value.ToString();
                string month = holidayDate.Substring(0, MONTH_TEXT_LENGH);
                bool foundInMonthText = false;
                foreach (string m in monthText)
                {
                    if (month.Equals(m, StringComparison.OrdinalIgnoreCase))
                    {
                        foundInMonthText = true;
                        break;
                    }
                }

                if (foundInMonthText)
                {
                    string day = holidayDate.Substring(MONTH_TEXT_LENGH + 1);
                    int iDay = 0;
                    bool converted = int.TryParse(day, out iDay);
                    if (converted)
                    {
                        if (iDay < GENERAL_MONTH_START && iDay > GENERAL_MONTH_END)
                        {
                            MessageBox.Show(this, String.Format("'{0}' is not valid date. Check the format", holidayDate),
                                AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            r.Cells[HOLIDAY_DATE_COLUMN_INDEX].Selected = true;
                            return;
                        }
                    }
                }
                else
                {
                    MessageBox.Show(this, String.Format("'{0}' is not valid date. Check the format", holidayDate),
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dgvHolidays.CurrentCell = dgvHolidays[HOLIDAY_DATE_COLUMN_INDEX, i];
                    dgvHolidays.BeginEdit(true);
                    return;
                }

                string holidayName = r.Cells[HOLIDAY_NAME_COLUMN_INDEX].Value.ToString();
                if (string.IsNullOrEmpty(holidayName))
                {
                    MessageBox.Show(this, "Holiday name can not be empty!",
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    dgvHolidays.CurrentCell = dgvHolidays[HOLIDAY_NAME_COLUMN_INDEX, i];
                    dgvHolidays.BeginEdit(true);
                    return;
                }

                foreach (var d in holidayDates)
                {
                    if (d.Equals(holidayDate, StringComparison.OrdinalIgnoreCase))
                    {
                        MessageBox.Show(this, String.Format("'{0}' is defined more than once!", holidayDate),
                        AppConfiguration.ApplicationName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        dgvHolidays.CurrentCell = dgvHolidays[HOLIDAY_DATE_COLUMN_INDEX, i];
                        dgvHolidays.BeginEdit(true);
                        return;
                    }
                }

                holidayDates.Add(holidayDate);
                holidayNames.Add(holidayName);
            }

            cboYear.Enabled = false;
            dgvHolidays.Enabled = false;
            btnSave.Enabled = false;
            btnReset.Enabled = false;
            btnCancel.Enabled = false;
            string saveButtonText = btnSave.Text;
            btnSave.Text = "Please wait...";
            Application.DoEvents();

            this.Cursor = Cursors.WaitCursor;
            Utilities.SaveHolidays(calendarYear, holidayDates, holidayNames);
            string saveDate = DateTime.Now.ToString("s");
            Utilities.SetSetting(AutoReminderSettings.AUTO_REMINDER_SETTING_SAVE_DATE, saveDate);
            PopulateCalendarYears();

            cboYear.Enabled = true;
            dgvHolidays.Enabled = true;
            btnReset.Enabled = true;
            btnCancel.Enabled = true;
            btnSave.Enabled = true;
            btnSave.Text = saveButtonText;
            this.Cursor = Cursors.Default;
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            CheckCalendarYear();
        }
    }
}
